package com.spring.gop.proj.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.gop.proj.interfaces.MovieDao;
import com.spring.gop.proj.interfaces.MovieService;
import com.spring.gop.proj.interfaces.TicketDao;
import com.spring.gop.proj.model.Buy;
import com.spring.gop.proj.model.Movie;
import com.spring.gop.proj.model.MovieAttach;
import com.spring.gop.proj.model.MovieChart;
import com.spring.gop.proj.model.MyPoint;
import com.spring.gop.proj.model.User;

@Service
public class MovieServiceImpl implements MovieService {

	@Autowired MovieDao movieDao;
	@Autowired TicketDao ticketDao;
	
	public List<Movie> selectMovies() {
		return movieDao.selectMovies();
	}
	
	public List<Movie> selectMovieForTitle(String searchMovieName) {
		return movieDao.selectMovieForTitle(searchMovieName);
	}
	
	public Movie selectMovie(int num) {
		Movie movie = movieDao.selectMovie(num);
		movie.setMovie_synopsis(movie.getMovie_synopsis().replaceAll("\r\n", "<br/>"));
		return movie;
	}
	
	public List<MovieAttach> selectMovieAttach(int num) {
		return movieDao.selectMovieAttach(num);
	}
	
	public List<MovieAttach> selectMovieBanner() {
		return movieDao.selectMovieBanner();
	}
	
	public List<MovieChart> selectMovieChart(int regyear, int regmonth) {
		return movieDao.selectMovieChart(regyear, regmonth);
	}
	
	public Buy selectBuyMovieForId(Map<String, Object> map) {
		return movieDao.selectBuyMovieForId(map);
	}
	
	public List<Buy> selectBuyListMovieForId(String member_id) {
		return movieDao.selectBuyListMovieForId(member_id);
	}
	
	@Transactional
	public void insertBuyMovie(Buy buy, User user) {
		
		/*
		1. 구매 내역에 추가 시킨다.
		2. 포인트 사용 내역에 추가 시킨다. (포인트 사용)
		3. 멤버 테이블의 포인트를 갱신 시킨다.
		4. 세션에 남긴다.
		*/
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		buy.setRegdate(sdf.format(cal.getTime()));
		movieDao.insertBuyMovie(buy);
		
		MyPoint myPoint = new MyPoint();
		myPoint.setPoint_note("포인트");
		myPoint.setMember_id(buy.getMember_id());
		myPoint.setPoint_title("영화 구매");
		myPoint.setPoint_value(buy.getMovie_price());
		myPoint.setPoint_chargedate(sdf.format(cal.getTime()));
		ticketDao.insertTicket(myPoint);
		
		user.setMember_point(user.getMember_point() - myPoint.getPoint_value());
		ticketDao.updateTicket(user);
	}
}

















































